package com.wzy.common.base.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/3/13 23:12
 * 4
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 向redis中存放字符串
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        try{
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存失效时间
     * @param key 键
     * @param time 秒
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        }catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String get(String key) {
        Object res = redisTemplate.opsForValue().get(key);
        return  res == null ? null : (String)res;
    }

    /**
     * 根据key 获取过期时间
     * @param key 不能为null
     * @return 返回0为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

}
